<template>
  <div class="resource-management">
    <h1>资源管理</h1>

    <!-- 文献上传 -->
    <el-card class="upload-section">
      <h2>文献上传</h2>
      <!-- 文献信息表单 -->
      <el-form :model="uploadForm" :rules="rules" ref="uploadFormRef" label-width="100px">
        <el-form-item label="文献标题" prop="title">
          <el-input v-model="uploadForm.title" placeholder="请输入文献标题" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="uploadForm.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-input v-model="uploadForm.year" placeholder="请输入年份" />
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload
              action="http://localhost:81/literature/upload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :limit="1"
              :file-list="fileList"
              :with-credentials="true"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">仅支持 PDF 文件，且不超过 10MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitUpload">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 搜索栏 -->
    <el-card class="search-section">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="文献标题">
          <el-input v-model="searchForm.title" placeholder="请输入文献标题" />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="searchForm.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="年份">
          <el-input v-model="searchForm.year" placeholder="请输入年份" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 文献列表 -->
    <el-card class="literature-section">
      <h2>文献管理</h2>
      <el-table :data="literatures" style="width: 100%">
        <el-table-column prop="title" label="文献标题" />
        <el-table-column prop="author" label="作者" />
        <el-table-column prop="year" label="年份" />
        <el-table-column prop="filePath" label="文件路径" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="text" @click="previewPDF(scope.row)">
              <el-icon><View /></el-icon> 预览
            </el-button>
            <el-button type="text" @click="downloadLiterature(scope.row)">
              <el-icon><Download /></el-icon> 下载
            </el-button>
            <el-button type="text" @click="disableLiterature(scope.row)" v-if="isAdmin">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
      />
    </el-card>


    <!-- 文献详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="文献详情">
      <el-form :model="literatureDetail" label-width="100px">
        <el-form-item label="文献标题">
          <el-input v-model="literatureDetail.title" disabled />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="literatureDetail.author" disabled />
        </el-form-item>
        <el-form-item label="年份">
          <el-input v-model="literatureDetail.year" disabled />
        </el-form-item>
        <el-form-item label="文件路径">
          <el-input v-model="literatureDetail.filePath" disabled />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import { handleError, handleSuccess } from '@/util/request';
import row from "element-ui/packages/row"; // 引入全局的请求处理工具

export default defineComponent({
  name: 'ResourceManagement',
  data() {
    return {
      user: {},
      fileList: [], // 上传的文件列表
      literatures: [], // 文献列表
      total: 0, // 总文献数
      pageSize: 10, // 每页大小
      currentPage: 1, // 当前页
      detailDialogVisible: false, // 详情对话框是否显示
      literatureDetail: {}, // 文献详情
      searchForm: {
        title: '', // 文献标题搜索条件
        author: '', // 作者搜索条件
        year: '', // 年份搜索条件
      },
      uploadForm: {
        title: '', // 文献标题
        author: '', // 作者
        year: '', // 年份
      },
      rules: {
        title: [
          { required: true, message: '请输入文献标题', trigger: 'blur' },
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
        ],
        year: [
          { required: true, message: '请输入年份', trigger: 'blur' },
          { pattern: /^\d{4}$/, message: '年份必须为 4 位数字', trigger: 'blur' }
        ],
      },
    };
  },
  created() {
    this.user = JSON.parse(localStorage.getItem('user'))
    this.fetchLiteraturePage();
  },
  computed: {
    isAdmin() {
      return this.user.role === '管理员';
    }
  },
  methods: {
    // 获取文献分页数据
    fetchLiteraturePage() {
      this.$http.get('/literature/page', {
        params: {
          title: this.searchForm.title,
          author: this.searchForm.author,
          year: this.searchForm.year,
          page: this.currentPage,
          size: this.pageSize,
        },
      })
          .then((response) => {
            if (response.data.code === 10000) {
              this.literatures = response.data.data.records; // 文献列表数据
              this.total = response.data.data.total; // 总记录数
            } else {
              this.$message.error(response.data.msg || '获取文献列表失败');
            }
          })
          .catch((error) => {
            handleError(error);
          });
    },
    // 提交上传
    // 提交上传
    submitUpload() {
      this.$refs.uploadFormRef.validate((valid) => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$message.error('请先选择文件');
            return;
          }

          // 构造 Literature 对象
          const literature = {
            title: this.uploadForm.title,
            author: this.uploadForm.author,
            year: this.uploadForm.year,
            filePath: this.fileList[0].filePath, // 从 fileList 中获取文件路径
          };

          // 调用保存接口
          this.$http.post('/literature/save', literature)
              .then((response) => {
                if (response.data.code === 10000) {
                  this.$message.success('文献保存成功');
                  this.fileList = []; // 清空文件列表
                  this.uploadForm = { title: '', author: '', year: '' }; // 清空表单
                  this.fetchLiteraturePage(); // 刷新文献列表
                } else {
                  this.$message.error(response.data.msg || '文献保存失败');
                }
              })
              .catch((error) => {
                handleError(error);
              });
        } else {
          this.$message.error('请填写完整的文献信息');
        }
      });
    },
    // 处理上传成功
    handleUploadSuccess(response, file) {
      if (response.code === 10000) {
        this.$message.success('文件上传成功');
        file.filePath = response.data.filePath; // 将文件路径保存到 file 对象中
        this.fileList = [file]; // 更新文件列表
      } else {
        this.$message.error(response.msg || '文件上传失败');
      }
    },
    // 处理上传失败
    handleUploadError(err, file) {
      handleError(err);
      this.$message.error(`文件 ${file.name} 上传失败，请重试或联系管理员。`);
    },
    // 上传前的校验
    beforeUpload(file) {
      const isPDF = file.type === 'application/pdf';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isPDF) {
        this.$message.error('只能上传 PDF 文件');
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 10MB');
      }

      return isPDF && isLt10M;
    },
    // 下载文献
    async downloadLiterature(literature) {
      try {
        const response = await this.$http.get(`/literature/download?id=${literature.id}`, {
          responseType: 'blob', // 确保响应类型为 blob
        });

        // 检查响应内容的类型
        if (response.headers['content-type'].includes('application/json')) {
          // 如果是 JSON，解析错误信息
          const reader = new FileReader();
          reader.onload = () => {
            const errorResponse = JSON.parse(reader.result);
            this.$message.error(errorResponse.message || '文件下载失败');
          };
          reader.readAsText(response.data);
        } else {
          // 如果是文件流，触发下载
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = url;
          const fileName = literature.filePath.split('/').pop(); // 从路径中提取文件名
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          window.URL.revokeObjectURL(url);
          document.body.removeChild(link);
          this.$message.success('文件下载成功');
        }
      } catch (error) {
        // 处理错误
        this.$message.error('文件下载失败: ' + error.message);
        console.error('文件下载失败:', error);
      }
    },
    // 查看文献详情
    async viewLiteratureDetail(literature) {
      try {
        const response = await this.$http.get(`/literature/detail?id=${literature.id}`);
        this.literatureDetail = response.data.data;
        this.detailDialogVisible = true;
      } catch (error) {
        handleError(error); // 使用全局的错误处理工具
      }
    },
    // 删除文献
    async disableLiterature(literature) {
      this.$confirm('确定要删除该文献吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$http.post('/literature/disable', {id:literature.id})
          this.$message("删除成功")
          this.fetchLiteraturePage(); // 刷新文献列表
        } catch (error) {
          handleError(error); // 使用全局的错误处理工具
        }
    })
    },
    // 分页切换
    handlePageChange(page) {
      this.currentPage = page; // 更新当前页
      this.fetchLiteraturePage(); // 重新获取数据
    },
    // 搜索文献
    handleSearch() {
      this.currentPage = 1; // 重置为第一页
      this.fetchLiteraturePage(); // 重新获取数据
    },
    // 重置搜索条件
    resetSearch() {
      this.searchForm.title = '';
      this.searchForm.author = '';
      this.searchForm.year = '';
      this.currentPage = 1; // 重置为第一页
      this.fetchLiteraturePage(); // 重新获取数据
    },
  },
});
</script>

<style scoped>
.resource-management {
  padding: 20px;
}

.upload-section,
.search-section,
.literature-section {
  margin-bottom: 20px;
}

h1 {
  margin-bottom: 20px;
}

h2 {
  margin-bottom: 10px;
}
</style>